from django.http import JsonResponse
from rest_framework import viewsets
from .models import Author, Post
from .serializers import AuthorSerializer, PostSerializer
from django.shortcuts import render
from rest_framework.permissions import IsAuthenticated
from django.views.decorators.csrf import csrf_exempt


class AuthorViewSet(viewsets.ModelViewSet):
    queryset = Author.objects.all()
    serializer_class = AuthorSerializer


class PostViewSet(viewsets.ModelViewSet):
    queryset = Post.objects.all()
    serializer_class = PostSerializer
    permission_classes = [IsAuthenticated]  # 保护此视图，要求用户认证


def blog_posts(request):
    return render(request, "blog/blog_posts.html")


def my_view(request):
    posts = Post.objects.all()  # 获取所有 Post 对象

    data = []
    for post in posts:
        post_data = {
            "id": post.id,
            "title": post.title,
            "content": post.text,
            # ... 添加其他需要的字段
        }
        data.append(post_data)

    return JsonResponse(data, safe=False)


@csrf_exempt  # 仅用于测试，生产环境中不要禁用 CSRF 保护
def upload_file(request):
    if request.method == "POST":
        if "file" in request.FILES:
            file = request.FILES["file"]
            file_name = file.name
            # 处理上传的文件，例如保存到磁盘
            with open(f"media/{file_name}", "wb+") as destination:
                for chunk in file.chunks():
                    destination.write(chunk)
            return JsonResponse({"message": f"File {file_name} uploaded successfully"})
        else:
            return JsonResponse({"error": "No file provided"}, status=400)
    else:
        return JsonResponse({"error": "Only POST requests are allowed"}, status=405)
